#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
综合场景测试报告生成器
Comprehensive Scenario Test Report Generator

该模块实现：
1. 整合所有场景测试结果
2. 生成综合分析报告
3. 风险评估和建议
4. 可视化图表生成
5. 执行摘要和详细报告
"""

import os
import sys
import json
import time
from typing import Dict, List, Optional, Any, Tuple
from dataclasses import dataclass, asdict
from datetime import datetime, timedelta
from enum import Enum
import base64

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 导入错误处理系统
from core.error_handler import (
    EnhancedErrorHandler, ErrorSeverity, ErrorCategory, 
    error_handler, handle_critical_error
)

class RiskLevel(Enum):
    """风险等级"""
    CRITICAL = "critical"
    HIGH = "high"
    MEDIUM = "medium"
    LOW = "low"
    INFO = "info"

class TestCategory(Enum):
    """测试类别"""
    PRIVILEGE_ESCALATION = "privilege_escalation"
    PERSISTENCE = "persistence"
    EDR_EVASION = "edr_evasion"
    LOG_CLEANUP = "log_cleanup"
    NETWORK_PENETRATION = "network_penetration"
    LATERAL_MOVEMENT = "lateral_movement"

@dataclass
class RiskAssessment:
    """风险评估"""
    category: str
    risk_level: RiskLevel
    impact_score: float  # 0-10
    likelihood_score: float  # 0-10
    overall_risk: float  # 0-100
    description: str
    recommendations: List[str]
    affected_systems: List[str]

@dataclass
class ComprehensiveReport:
    """综合报告"""
    report_id: str
    generation_time: datetime
    target_environment: str
    test_duration: float
    total_tests: int
    successful_tests: int
    failed_tests: int
    overall_success_rate: float
    risk_assessments: List[RiskAssessment]
    executive_summary: str
    detailed_findings: Dict[str, Any]
    recommendations: List[str]
    next_steps: List[str]

class ComprehensiveReportGenerator:
    """综合报告生成器"""
    
    def __init__(self, target_environment: str = "101.37.80.173"):
        self.target_environment = target_environment
        self.test_results = {}
        self.risk_assessments = []
        self.report_data = {}
        
        # 初始化错误处理器
        self.error_handler = EnhancedErrorHandler(
            log_dir="logs/report_generator",
            enable_recovery=True
        )
        
    @error_handler(severity=ErrorSeverity.HIGH, category=ErrorCategory.VALIDATION)
    def load_test_results(self, results_data: Dict[str, Any]) -> None:
        """加载测试结果数据"""
        if not isinstance(results_data, dict):
            raise ValueError(f"测试结果数据必须是字典类型，当前类型: {type(results_data)}")
        
        self.test_results = results_data
        print(f"📊 已加载 {len(results_data)} 个测试类别的结果")
    
    @error_handler(severity=ErrorSeverity.MEDIUM, category=ErrorCategory.EXECUTION)
    def analyze_privilege_escalation_results(self, results: List[Any]) -> RiskAssessment:
        """分析权限提升测试结果"""
        if not results:
            return self._create_no_data_assessment("权限提升")
        
        success_rate = sum(1 for r in results if getattr(r, 'success_rate', 0) > 0.7) / len(results)
        avg_stealth = sum(getattr(r, 'stealth_rating', 0) for r in results) / len(results)
        
        # 计算风险评分
        impact_score = 9.0  # 权限提升影响很高
        likelihood_score = success_rate * 10
        overall_risk = (impact_score * likelihood_score) / 10
        
        # 确定风险等级
        if overall_risk >= 80:
            risk_level = RiskLevel.CRITICAL
        elif overall_risk >= 60:
            risk_level = RiskLevel.HIGH
        elif overall_risk >= 40:
            risk_level = RiskLevel.MEDIUM
        else:
            risk_level = RiskLevel.LOW
        
        return RiskAssessment(
            category="权限提升",
            risk_level=risk_level,
            impact_score=impact_score,
            likelihood_score=likelihood_score,
            overall_risk=overall_risk,
            description=f"权限提升测试成功率为 {success_rate:.1%}，平均隐蔽性 {avg_stealth:.1%}。"
                       f"系统存在权限提升风险。",
            recommendations=[
                "加强系统补丁管理，及时修复已知漏洞",
                "限制SUID/SGID程序的使用",
                "定期审查sudo配置",
                "实施最小权限原则",
                "部署EDR解决方案监控异常权限提升"
            ],
            affected_systems=[self.target_environment]
        )
    
    @error_handler(severity=ErrorSeverity.MEDIUM, category=ErrorCategory.EXECUTION)
    def analyze_persistence_results(self, results: List[Any]) -> RiskAssessment:
        """分析持久化测试结果"""
        if not results:
            return self._create_no_data_assessment("持久化机制")
        
        # 使用survival_rate代替success_rate
        success_rate = sum(1 for r in results if getattr(r, 'survival_rate', 0) > 0.6) / len(results)
        avg_stealth = sum(getattr(r, 'stealth_rating', 0) for r in results) / len(results)
        
        impact_score = 8.5  # 持久化影响高
        likelihood_score = success_rate * 10
        overall_risk = (impact_score * likelihood_score) / 10
        
        if overall_risk >= 75:
            risk_level = RiskLevel.CRITICAL
        elif overall_risk >= 55:
            risk_level = RiskLevel.HIGH
        elif overall_risk >= 35:
            risk_level = RiskLevel.MEDIUM
        else:
            risk_level = RiskLevel.LOW
        
        return RiskAssessment(
            category="持久化机制",
            risk_level=risk_level,
            impact_score=impact_score,
            likelihood_score=likelihood_score,
            overall_risk=overall_risk,
            description=f"持久化机制测试成功率为 {success_rate:.1%}，平均隐蔽性 {avg_stealth:.1%}。"
                       f"攻击者可能建立多种持久化后门。",
            recommendations=[
                "定期检查系统启动项和定时任务",
                "监控SSH密钥变化",
                "审查系统服务配置",
                "实施文件完整性监控",
                "建立基线配置管理"
            ],
            affected_systems=[self.target_environment]
        )
    
    @error_handler(severity=ErrorSeverity.MEDIUM, category=ErrorCategory.EXECUTION)
    def analyze_edr_evasion_results(self, results: List[Any]) -> RiskAssessment:
        """分析EDR规避测试结果"""
        if not results:
            return self._create_no_data_assessment("EDR规避")
        
        success_rate = sum(1 for r in results if getattr(r, 'success_rate', 0) > 0.7) / len(results)
        avg_stealth = sum(getattr(r, 'stealth_rating', 0) for r in results) / len(results)
        
        impact_score = 7.5  # EDR规避影响中高
        likelihood_score = success_rate * 10
        overall_risk = (impact_score * likelihood_score) / 10
        
        if overall_risk >= 70:
            risk_level = RiskLevel.HIGH
        elif overall_risk >= 50:
            risk_level = RiskLevel.MEDIUM
        elif overall_risk >= 30:
            risk_level = RiskLevel.LOW
        else:
            risk_level = RiskLevel.INFO
        
        return RiskAssessment(
            category="EDR规避",
            risk_level=risk_level,
            impact_score=impact_score,
            likelihood_score=likelihood_score,
            overall_risk=overall_risk,
            description=f"EDR规避测试成功率为 {success_rate:.1%}，平均隐蔽性 {avg_stealth:.1%}。"
                       f"现有安全防护可能被绕过。",
            recommendations=[
                "升级EDR解决方案到最新版本",
                "启用行为分析和机器学习检测",
                "配置多层防护策略",
                "定期更新检测规则",
                "实施零信任网络架构"
            ],
            affected_systems=[self.target_environment]
        )
    
    @error_handler(severity=ErrorSeverity.MEDIUM, category=ErrorCategory.EXECUTION)
    def analyze_log_cleanup_results(self, results: List[Any]) -> RiskAssessment:
        """分析日志清理测试结果"""
        if not results:
            return self._create_no_data_assessment("日志清理")
        
        cleanup_rate = sum(getattr(r, 'cleanup_rate', 0) for r in results) / len(results)
        avg_stealth = sum(getattr(r, 'stealth_rating', 0) for r in results) / len(results)
        
        impact_score = 6.0  # 日志清理影响中等
        likelihood_score = cleanup_rate * 10
        overall_risk = (impact_score * likelihood_score) / 10
        
        if overall_risk >= 60:
            risk_level = RiskLevel.HIGH
        elif overall_risk >= 40:
            risk_level = RiskLevel.MEDIUM
        elif overall_risk >= 20:
            risk_level = RiskLevel.LOW
        else:
            risk_level = RiskLevel.INFO
        
        return RiskAssessment(
            category="日志清理",
            risk_level=risk_level,
            impact_score=impact_score,
            likelihood_score=likelihood_score,
            overall_risk=overall_risk,
            description=f"日志清理测试平均清理率为 {cleanup_rate:.1%}，平均隐蔽性 {avg_stealth:.1%}。"
                       f"攻击痕迹可能被有效清除。",
            recommendations=[
                "实施集中化日志管理",
                "启用日志完整性保护",
                "配置实时日志转发",
                "建立日志备份机制",
                "部署SIEM解决方案"
            ],
            affected_systems=[self.target_environment]
        )
    
    @error_handler(severity=ErrorSeverity.MEDIUM, category=ErrorCategory.EXECUTION)
    def analyze_network_penetration_results(self, results: List[Any]) -> RiskAssessment:
        """分析网络渗透测试结果"""
        if not results:
            return self._create_no_data_assessment("网络渗透")
        
        success_rate = sum(getattr(r, 'success_rate', 0) for r in results) / len(results)
        avg_stealth = sum(getattr(r, 'stealth_rating', 0) for r in results) / len(results)
        
        impact_score = 8.0  # 网络渗透影响高
        likelihood_score = success_rate * 10
        overall_risk = (impact_score * likelihood_score) / 10
        
        if overall_risk >= 75:
            risk_level = RiskLevel.CRITICAL
        elif overall_risk >= 55:
            risk_level = RiskLevel.HIGH
        elif overall_risk >= 35:
            risk_level = RiskLevel.MEDIUM
        else:
            risk_level = RiskLevel.LOW
        
        return RiskAssessment(
            category="网络渗透",
            risk_level=risk_level,
            impact_score=impact_score,
            likelihood_score=likelihood_score,
            overall_risk=overall_risk,
            description=f"网络渗透测试成功率为 {success_rate:.1%}，平均隐蔽性 {avg_stealth:.1%}。"
                       f"网络安全防护存在薄弱环节。",
            recommendations=[
                "实施网络分段和微分段",
                "部署入侵检测系统(IDS)",
                "加强网络访问控制",
                "定期进行漏洞扫描",
                "建立网络流量监控"
            ],
            affected_systems=[self.target_environment]
        )
    
    def _create_no_data_assessment(self, category: str) -> RiskAssessment:
        """创建无数据的风险评估"""
        return RiskAssessment(
            category=category,
            risk_level=RiskLevel.INFO,
            impact_score=0.0,
            likelihood_score=0.0,
            overall_risk=0.0,
            description=f"{category}测试未执行或无有效数据。",
            recommendations=["执行相关安全测试以评估风险"],
            affected_systems=[]
        )
    
    def generate_risk_assessments(self) -> List[RiskAssessment]:
        """生成风险评估"""
        print("🔍 生成风险评估...")
        
        assessments = []
        
        # 分析各类测试结果
        if "privilege_escalation" in self.test_results:
            assessments.append(self.analyze_privilege_escalation_results(
                self.test_results["privilege_escalation"]))
        
        if "persistence" in self.test_results:
            assessments.append(self.analyze_persistence_results(
                self.test_results["persistence"]))
        
        if "edr_evasion" in self.test_results:
            assessments.append(self.analyze_edr_evasion_results(
                self.test_results["edr_evasion"]))
        
        if "log_cleanup" in self.test_results:
            assessments.append(self.analyze_log_cleanup_results(
                self.test_results["log_cleanup"]))
        
        if "network_penetration" in self.test_results:
            assessments.append(self.analyze_network_penetration_results(
                self.test_results["network_penetration"]))
        
        self.risk_assessments = assessments
        
        # 打印风险评估摘要
        for assessment in assessments:
            risk_emoji = {
                RiskLevel.CRITICAL: "🔴",
                RiskLevel.HIGH: "🟠", 
                RiskLevel.MEDIUM: "🟡",
                RiskLevel.LOW: "🟢",
                RiskLevel.INFO: "ℹ️"
            }
            print(f"  {risk_emoji[assessment.risk_level]} {assessment.category}: "
                  f"{assessment.risk_level.value.upper()} (风险值: {assessment.overall_risk:.1f})")
        
        return assessments
    
    def generate_executive_summary(self) -> str:
        """生成执行摘要"""
        total_tests = sum(len(results) for results in self.test_results.values())
        
        # 计算总体风险
        if self.risk_assessments:
            avg_risk = sum(r.overall_risk for r in self.risk_assessments) / len(self.risk_assessments)
            critical_risks = len([r for r in self.risk_assessments if r.risk_level == RiskLevel.CRITICAL])
            high_risks = len([r for r in self.risk_assessments if r.risk_level == RiskLevel.HIGH])
        else:
            avg_risk = 0
            critical_risks = 0
            high_risks = 0
        
        summary = f"""## 执行摘要

本次全方位授权渗透测试针对目标环境 {self.target_environment} 进行了综合安全评估。

### 测试概览
- **测试范围**: 权限提升、持久化机制、EDR规避、日志清理、网络渗透
- **测试数量**: {total_tests} 项测试
- **测试时间**: {datetime.now().strftime('%Y年%m月%d日')}
- **整体风险评分**: {avg_risk:.1f}/100

### 关键发现
- **严重风险**: {critical_risks} 项
- **高风险**: {high_risks} 项
- **总体安全态势**: {"需要立即关注" if avg_risk >= 70 else "需要改进" if avg_risk >= 40 else "相对安全"}

### 主要威胁
"""
        
        # 添加主要威胁
        high_risk_categories = [r for r in self.risk_assessments 
                               if r.risk_level in [RiskLevel.CRITICAL, RiskLevel.HIGH]]
        
        if high_risk_categories:
            for risk in high_risk_categories:
                summary += f"- **{risk.category}**: {risk.description}\n"
        else:
            summary += "- 未发现严重或高风险威胁\n"
        
        summary += f"""
### 建议优先级
1. **立即处理**: 严重和高风险项目
2. **短期改进**: 中等风险项目和基础安全加固
3. **长期规划**: 安全架构优化和持续监控

详细的技术发现和建议请参阅后续章节。
"""
        
        return summary
    
    def generate_detailed_findings(self) -> Dict[str, Any]:
        """生成详细发现"""
        findings = {}
        
        for category, results in self.test_results.items():
            if not results:
                continue
            
            category_findings = {
                "test_count": len(results),
                "success_rate": 0,
                "techniques": [],
                "key_findings": [],
                "recommendations": []
            }
            
            # 计算成功率和收集技术
            successful_tests = 0
            all_techniques = []
            all_recommendations = []
            
            for result in results:
                if hasattr(result, 'success_rate') and result.success_rate > 0.5:
                    successful_tests += 1
                
                if hasattr(result, 'techniques_used'):
                    all_techniques.extend(result.techniques_used)
                
                if hasattr(result, 'recommendations'):
                    all_recommendations.extend(result.recommendations)
            
            category_findings["success_rate"] = successful_tests / len(results)
            category_findings["techniques"] = list(set(all_techniques))
            category_findings["recommendations"] = list(set(all_recommendations))
            
            # 生成关键发现
            if category == "privilege_escalation":
                category_findings["key_findings"] = [
                    f"发现 {len(category_findings['techniques'])} 种权限提升技术",
                    f"成功率达到 {category_findings['success_rate']:.1%}",
                    "SUID/SGID程序和Sudo配置是主要攻击向量"
                ]
            elif category == "persistence":
                category_findings["key_findings"] = [
                    f"测试了 {len(category_findings['techniques'])} 种持久化方法",
                    "SSH密钥和定时任务是常用持久化手段",
                    "系统服务持久化隐蔽性较高"
                ]
            elif category == "edr_evasion":
                category_findings["key_findings"] = [
                    f"EDR规避技术成功率 {category_findings['success_rate']:.1%}",
                    "内存混淆和进程注入效果显著",
                    "反调试技术可有效对抗分析"
                ]
            elif category == "log_cleanup":
                category_findings["key_findings"] = [
                    "日志清理技术多样化",
                    "时间戳修改和选择性删除最常用",
                    "内存痕迹清理效果最佳但持续时间短"
                ]
            elif category == "network_penetration":
                category_findings["key_findings"] = [
                    f"网络发现和横向移动成功率 {category_findings['success_rate']:.1%}",
                    "SSH密钥复用是最隐蔽的移动方法",
                    "多种数据渗透通道可用"
                ]
            
            findings[category] = category_findings
        
        return findings
    
    def generate_recommendations(self) -> List[str]:
        """生成综合建议"""
        recommendations = [
            "## 综合安全建议",
            "",
            "### 立即行动项",
            "1. **修复高危漏洞**: 优先处理严重和高风险发现",
            "2. **加强访问控制**: 实施最小权限原则",
            "3. **部署监控**: 建立实时安全监控和告警",
            "",
            "### 短期改进 (1-3个月)",
            "4. **安全加固**: 系统配置安全基线",
            "5. **员工培训**: 提高安全意识和技能",
            "6. **应急响应**: 建立事件响应流程",
            "",
            "### 长期规划 (3-12个月)",
            "7. **架构优化**: 实施零信任网络架构",
            "8. **持续改进**: 建立持续安全评估机制",
            "9. **合规管理**: 确保符合相关安全标准"
        ]
        
        # 添加特定类别的建议
        for assessment in self.risk_assessments:
            if assessment.risk_level in [RiskLevel.CRITICAL, RiskLevel.HIGH]:
                recommendations.extend([
                    f"",
                    f"### {assessment.category}专项建议"
                ])
                recommendations.extend([f"- {rec}" for rec in assessment.recommendations])
        
        return recommendations
    
    @error_handler(severity=ErrorSeverity.CRITICAL, category=ErrorCategory.EXECUTION)
    def generate_comprehensive_report(self) -> ComprehensiveReport:
        """生成综合报告"""
        if not self.test_results:
            raise ValueError("没有测试结果数据，请先调用 load_test_results()")
            
        print("📋 生成综合测试报告...")
        
        # 生成各部分内容
        risk_assessments = self.generate_risk_assessments()
        executive_summary = self.generate_executive_summary()
        detailed_findings = self.generate_detailed_findings()
        recommendations = self.generate_recommendations()
        
        # 计算总体统计
        total_tests = sum(len(results) for results in self.test_results.values())
        successful_tests = 0
        failed_tests = 0
        
        for results in self.test_results.values():
            for result in results:
                if hasattr(result, 'success_rate'):
                    if result.success_rate > 0.5:
                        successful_tests += 1
                    else:
                        failed_tests += 1
        
        overall_success_rate = successful_tests / total_tests if total_tests > 0 else 0
        
        report = ComprehensiveReport(
            report_id=f"COMP_TEST_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
            generation_time=datetime.now(),
            target_environment=self.target_environment,
            test_duration=0.0,  # 将在实际运行时计算
            total_tests=total_tests,
            successful_tests=successful_tests,
            failed_tests=failed_tests,
            overall_success_rate=overall_success_rate,
            risk_assessments=risk_assessments,
            executive_summary=executive_summary,
            detailed_findings=detailed_findings,
            recommendations=recommendations,
            next_steps=[
                "制定风险缓解计划",
                "实施优先级安全控制措施",
                "建立持续监控机制",
                "定期进行安全评估",
                "更新安全策略和程序"
            ]
        )
        
        return report
    
    @error_handler(severity=ErrorSeverity.HIGH, category=ErrorCategory.IO)
    def export_report_markdown(self, report: ComprehensiveReport) -> str:
        """导出Markdown格式报告"""
        markdown_content = f"""# 全方位授权渗透测试综合报告

**报告ID**: {report.report_id}
**生成时间**: {report.generation_time.strftime('%Y年%m月%d日 %H:%M:%S')}
**目标环境**: {report.target_environment}

---

{report.executive_summary}

## 风险评估矩阵

| 类别 | 风险等级 | 影响评分 | 可能性评分 | 总体风险 | 描述 |
|------|----------|----------|------------|----------|------|
"""
        
        for assessment in report.risk_assessments:
            risk_emoji = {
                RiskLevel.CRITICAL: "🔴",
                RiskLevel.HIGH: "🟠",
                RiskLevel.MEDIUM: "🟡", 
                RiskLevel.LOW: "🟢",
                RiskLevel.INFO: "ℹ️"
            }
            markdown_content += f"| {assessment.category} | {risk_emoji[assessment.risk_level]} {assessment.risk_level.value.upper()} | {assessment.impact_score:.1f} | {assessment.likelihood_score:.1f} | {assessment.overall_risk:.1f} | {assessment.description} |\n"
        
        markdown_content += f"""
## 测试统计

- **总测试数**: {report.total_tests}
- **成功测试**: {report.successful_tests}
- **失败测试**: {report.failed_tests}
- **总体成功率**: {report.overall_success_rate:.1%}

## 详细技术发现

"""
        
        for category, findings in report.detailed_findings.items():
            markdown_content += f"""### {category.replace('_', ' ').title()}

**测试数量**: {findings['test_count']}
**成功率**: {findings['success_rate']:.1%}

**关键发现**:
{chr(10).join(f'- {finding}' for finding in findings['key_findings'])}

**使用技术**:
{chr(10).join(f'- {tech}' for tech in findings['techniques'][:10])}  # 限制显示数量

**技术建议**:
{chr(10).join(f'- {rec}' for rec in findings['recommendations'][:5])}

---

"""
        
        markdown_content += f"""
{chr(10).join(report.recommendations)}

## 下一步行动

{chr(10).join(f'{i+1}. {step}' for i, step in enumerate(report.next_steps))}

---

**报告生成时间**: {datetime.now().strftime('%Y年%m月%d日 %H:%M:%S')}
**报告版本**: 1.0
"""
        
        return markdown_content
    
    @error_handler(severity=ErrorSeverity.HIGH, category=ErrorCategory.IO)
    def export_report_json(self, report: ComprehensiveReport) -> str:
        """导出JSON格式报告"""
        # 转换为可序列化的字典
        report_dict = {
            "report_id": report.report_id,
            "generation_time": report.generation_time.isoformat(),
            "target_environment": report.target_environment,
            "test_duration": report.test_duration,
            "total_tests": report.total_tests,
            "successful_tests": report.successful_tests,
            "failed_tests": report.failed_tests,
            "overall_success_rate": report.overall_success_rate,
            "risk_assessments": [
                {
                    "category": ra.category,
                    "risk_level": ra.risk_level.value,
                    "impact_score": ra.impact_score,
                    "likelihood_score": ra.likelihood_score,
                    "overall_risk": ra.overall_risk,
                    "description": ra.description,
                    "recommendations": ra.recommendations,
                    "affected_systems": ra.affected_systems
                }
                for ra in report.risk_assessments
            ],
            "executive_summary": report.executive_summary,
            "detailed_findings": report.detailed_findings,
            "recommendations": report.recommendations,
            "next_steps": report.next_steps
        }
        
        return json.dumps(report_dict, ensure_ascii=False, indent=2)

def main():
    """主函数"""
    print("📋 综合场景测试报告生成器")
    print("=" * 40)
    
    # 创建报告生成器
    generator = ComprehensiveReportGenerator()
    
    # 模拟测试结果数据（实际使用时会从各个测试模块加载）
    mock_results = {
        "privilege_escalation": [
            type('MockResult', (), {
                'success_rate': 0.8,
                'stealth_rating': 0.7,
                'techniques_used': ['SUID利用', 'Sudo配置错误'],
                'recommendations': ['加强权限管理', '定期安全审计']
            })()
        ],
        "persistence": [
            type('MockResult', (), {
                'success_rate': 0.75,
                'stealth_rating': 0.85,
                'techniques_used': ['SSH密钥', '定时任务'],
                'recommendations': ['监控启动项', '检查SSH配置']
            })()
        ]
    }
    
    # 加载测试结果
    generator.load_test_results(mock_results)
    
    # 生成综合报告
    report = generator.generate_comprehensive_report()
    
    # 导出报告
    markdown_report = generator.export_report_markdown(report)
    json_report = generator.export_report_json(report)
    
    # 保存报告文件
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    
    markdown_file = f"comprehensive_report_{timestamp}.md"
    with open(markdown_file, 'w', encoding='utf-8') as f:
        f.write(markdown_report)
    
    json_file = f"comprehensive_report_{timestamp}.json"
    with open(json_file, 'w', encoding='utf-8') as f:
        f.write(json_report)
    
    print(f"\n📋 报告已生成:")
    print(f"  Markdown: {markdown_file}")
    print(f"  JSON: {json_file}")

if __name__ == "__main__":
    main()